package com.suishoupai.xmb.service;

import com.suishoupai.xmb.dao.*;
import com.suishoupai.xmb.entity.*;
import com.suishoupai.xmb.exception.XmbException;
import com.suishoupai.xmb.utils.ParticipleUtil;
import com.suishoupai.xmb.utils.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by caojian on 2017/3/22.
 */
@Service
public class UserSaleService {
    @Autowired
    private CutUserSaleMapper cutSaleMapper;
    @Autowired
    private UserSaleMapper userSaleMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CutAuthMapper cutAuthMapper;
    @Autowired
    private SearchMapper searchMapper;
    @Autowired
    private CutSearchMapper cutSearchMapper;
    @Autowired
    private EmailSecurityMapper emailSecurityMapper;
    @Autowired
    private DeliveryDiscountMapper deliveryDiscountMapper;
    @Autowired
    private CutDeliveryDiscountMapper cutDeliveryDiscountMapper;
    @Autowired
    private HuanxinService huanxinService;

    @Value("${sale.deliveryDiscount-max}")
    private int deliveryDiscountMax;

    public List<UserSale> getAllSale() {
        return cutSaleMapper.selectAll();
    }

    /**
     * 获取可用店铺
     *
     * @param xiaoquId
     * @return
     */
    public List<UserSale> getSaleListByXiaoquId(long xiaoquId) {
        return cutSaleMapper.selectSaleListByXiaoquId(xiaoquId);
    }

    /**
     * 添加商家
     *
     * @param cutUserSale
     * @param auth
     */
    @Transactional
    public void addSale(CutUserSale cutUserSale, Auth auth) {
        cutUserSale.getUser().setCreateTime(System.currentTimeMillis());
        cutUserSale.getUserSale().setCreateTime(System.currentTimeMillis());
        auth.setUpdateTime(System.currentTimeMillis());
        String email = cutUserSale.getUser().getEmail();
        String password = cutUserSale.getUser().getPassword();
        String jPassword = PasswordUtil.encoder(email, password);
        cutUserSale.getUser().setPassword(jPassword);
        if (userMapper.insertSelective(cutUserSale.getUser()) == 0) {
            throw new RuntimeException("插入失败。抛出异常，让事务回滚。");
        }
        try {
            huanxinService.registeredUser(cutUserSale.getUser().getId() + "", password);//密码无需加密
        } catch (XmbException e) {
            throw new RuntimeException("环信用户注册失败！");
        }
        cutUserSale.getUserSale().setUserId(cutUserSale.getUser().getId());
        if (userSaleMapper.insertSelective(cutUserSale.getUserSale()) == 0) {
            throw new RuntimeException("插入失败。抛出异常，让事务回滚。");
        }
        if (cutAuthMapper.deleteByPrimaryKey(auth.getEmail(), auth.getType()) == 0) {
            throw new RuntimeException("删除失败。抛出异常，让事务回滚。");
        }
        EmailSecurity emailSecurity = new EmailSecurity();
        emailSecurity.setEmail(email);
        if (emailSecurityMapper.insertSelective(emailSecurity) == 0) {
            throw new RuntimeException("插入失败。抛出异常，让事务回滚。");
        }
        Search search = new Search();
        search.setDid(cutUserSale.getUser().getId());
        search.setType(SearchTypeEnum.SALE.getValue());
        search.setName(ParticipleUtil.participle(cutUserSale.getUserSale().getName()));
        if (searchMapper.insert(search) == 0) {
            throw new RuntimeException("插入失败！");
        }
    }

    public CutUserSale getCutUserSaleByUserId(long saleId) {
        CutUserSale cutUserSale = cutSaleMapper.selectByPrimaryKey(saleId);
        cutUserSale.getUser().setPassword("");
        return cutUserSale;
    }

    @Transactional
    public void updateUserSale(UserSale userSale) {
        if (cutSaleMapper.updateByPrimaryKeySelective(userSale) == 0) {
            throw new RuntimeException("更新失败");
        }
        if (userSale.getName() != null) {
            Search search = new Search();
            search.setDid(userSale.getUserId());
            search.setType(SearchTypeEnum.SALE.getValue());
            search.setName(ParticipleUtil.participle(userSale.getName()));
            if (cutSearchMapper.updateByPrimaryKeySelective(search) == 0) {
                throw new RuntimeException("更新失败！");
            }
        }
    }

    @Transactional
    public void addDeliveryDiscount(DeliveryDiscount deliveryDiscount) throws XmbException {
        long saleId = deliveryDiscount.getSaleId();
        CutUserSale cutUserSale = cutSaleMapper.selectByPrimaryKey(saleId);
        if (cutUserSale.getUserSale().getDeliveryDiscountNumber() >= deliveryDiscountMax) {
            throw XmbException.newError("当前配送优惠已达最大值（" + deliveryDiscountMax + "）");
        }
        if (cutSaleMapper.addDeliveryDiscountNumber(saleId, deliveryDiscountMax) == 0) {
            throw new RuntimeException("添加失败！");
        }
        if (deliveryDiscountMapper.insertSelective(deliveryDiscount) == 0) {
            throw new RuntimeException("添加失败！");
        }
    }

    @Transactional
    public void removeDeliveryDiscount(long saleId, long deliveryDiscountId) throws XmbException {
        DeliveryDiscount deliveryDiscount = cutDeliveryDiscountMapper.selectByPrimaryKey(deliveryDiscountId);
        if (deliveryDiscount == null) {
            return;
        }
        if (deliveryDiscount.getSaleId() != saleId) {
            throw XmbException.newError("权限不足。");
        }
        if (cutDeliveryDiscountMapper.deleteByPrimaryKey(deliveryDiscountId) == 0) {
            throw new RuntimeException("移除失败！");
        }
        if (cutSaleMapper.reduceDeliveryDiscountNumber(saleId) == 0) {
            throw new RuntimeException("移除失败！");
        }
    }
}
